package com.ddone.helper;

import com.ddone.model.auth.SysMenu;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ddone
 * @date 2024/3/29-21:33
 *   <p>
 *   根据菜单数据构建菜单树的工具类
 *   </p>
 *
 *   构建逻辑
 *      1.找到1级菜单
 *      2.对每个1节菜单,找到其子菜单并添加到其内部
 *      3.循环查找子菜单是否有菜单
 */
public class MenuHelper {
    /**
     * 使用递归方法建菜单
     * @param sysMenuList
     * @return
     */
    // public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
    //     List<SysMenu> trees = new ArrayList<>();
    //     for (SysMenu sysMenu : sysMenuList) {
    //         if (sysMenu.getParentId() == 0) {
    //             trees.add(findChildren(sysMenu,sysMenuList));
    //         }
    //     }
    //     return trees;
    // }

    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        return sysMenuList.stream()
                .filter(menu -> menu.getParentId() == 0)
                .map(menu -> findChildren(menu,sysMenuList))
                .collect(Collectors.toList());
    }
    /**
     * 递归查找子节点
     * @param menuList
     * @return
     */
    // public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> menuList) {
    //     sysMenu.setChildren(new ArrayList<SysMenu>());
    //     for (SysMenu item : menuList) {
    //         if(sysMenu.getId().longValue() == item.getParentId().longValue()) {
    //             if (sysMenu.getChildren() == null) {
    //                 sysMenu.setChildren(new ArrayList<>());
    //             }
    //             sysMenu.getChildren().add(findChildren(item,menuList));
    //         }
    //     }
    //     return sysMenu;
    // }

    public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> menuList) {
        List<SysMenu> childrenList = menuList.stream()
                .filter(menu -> sysMenu.getId().equals(menu.getParentId()))
                .map(item -> findChildren(item, menuList))
                .collect(Collectors.toList());
        sysMenu.setChildren(childrenList);
        return sysMenu;
    }
}
